<template>
	<!-- index.wxml -->
	<view class="box">
		<view class="container print">
			<view class="button-area" @tap="isModel=true">
				<ble-button size="large" iconWidth="40" iconHeight="31" icon="image">打印</ble-button>
			</view>
		</view>
		<view class="imgs" style="height: 100vh;">
			<u-album :urls="imageSrcArr"></u-album>
		</view>
		<canvas v-for="(item,i) in imageSrcArr" :key="i" :canvas-id="`canvas${i}`"
			style="width: 370px;height: 650px;background-color: #fff;" class="canvas"></canvas>

		<u-modal :show="isModel" title="提示" @cancel="isModel=false" @confirm="pushImg" showCancelButton
			content='你确定要打印吗？'></u-modal>
	</view>

</template>

<script>
	import bleButton from '../../components/button';
	import blePanel from '../../components/panel';
	import request from '../../utils/api/request.js'
	// index.js
	const {
		LAST_CONNECTED_DEVICE
	} = require('../../utils/constant');
	const {
		arrayBufferToHex
	} = require('../../utils/util');
	const PrinterTspl = require('../../utils/print/dll/printerTspl');
	export default {
		components: {
			bleButton,
			blePanel
		},
		data() {
			return {
				currentDevice: null,
				imageSrcArr: ['https://api.hmzfxt.com/profile/imgs/53467943.png'],
				isModel: false
			};
		},
		async onLoad() {
			try {
				const lastDevice = uni.getStorageSync(LAST_CONNECTED_DEVICE);
				this.currentDevice = lastDevice
				const code = uni.getStorageSync('code')
				const res = await request({
					url: `mp/zyCuttingbedInfo/selectPrint?id=${code}`
				})
				if (res.code == 200) {
					console.log(res.data, 'res.data');
					this.imageSrcArr = res.data
					// this.$nextTick(() => {
					// 	this.imageSrcArr.forEach((item, i) => {
					// 		// this.imageSrc = item
					// 		this.printImage(item, i)
					// 	})
					// })
				} else {
					uni.$u.toast('订单出错请重新扫码')
				}

			} catch (e) {
				//TODO handle the exception
			}


		},
		methods: {
			pushImg() {

				this.imageSrcArr.forEach((item, i) => {
					this.printImage(item, i)
				})
				this.isModel = false
			},
			printImage(item, i) {
				uni.showLoading({
					title: '打印中...'
				})
				let imageWidth = 370;
				let imageHeight = 650;
				let that = this;
				// 获取图片信息
				uni.getImageInfo({
					src: item,
					success: function(res) {
						// 图片的宽度
						imageWidth = res.width;
						// 图片的高度
						// imageHeight = res.height;
						let printerJobs = new PrinterTspl({
							printerType: 'Thermal'
						});
						that.drawImageFun(i, res.path, imageWidth, imageHeight, () => {
							uni.canvasGetImageData({
								canvasId: 'canvas' + i,
								x: 0,
								y: 0,
								width: imageWidth,
								height: imageHeight,
								success: function(res) {
									printerJobs.sizeBymm(38, 90).gapBymm(5, 0).direction(1).cls().bitmap(0, 120, 0, res)
										.print(1);
									that.writeBLECharacteristicValue(printerJobs);
									uni.hideLoading()
								},
								fail: function(err) {
									console.log('canvasGetImageData err', err);
								}
							});
						});
					}
				});
			},

			drawImageFun(i, url, width, height, callback) {
				const ctx = uni.createCanvasContext(`canvas${i}`, this)
				// 假设原始图像路径为 image.jpg
				const imagePath = url;
				// 将原始图像绘制到Canvas上
				ctx.drawImage(imagePath, 0, 0, width, height);
				// 获取图像数据
				ctx.draw(false, () => {
					uni.canvasGetImageData({
						canvasId: `canvas${i}`,
						x: 0,
						y: 0,
						width,
						height,
						success: (res) => {
							const imageData = res.data;
							// 反转每个像素的颜色
							for (let i = 0; i < imageData.length; i += 4) {
								imageData[i] = 255 - imageData[i]; // 红色
								imageData[i + 1] = 255 - imageData[i + 1]; // 绿色
								imageData[i + 2] = 255 - imageData[i + 2]; // 蓝色
							}
							// 将修改后的图像数据绘制到Canvas上
							uni.canvasPutImageData({
								canvasId: `canvas${i}`,
								data: imageData,
								x: 0,
								y: 0,
								width,
								height,
								success: () => {
									// 将Canvas转换为图片并显示
									uni.canvasToTempFilePath({
										canvasId: `canvas${i}`,
										success: (res) => {
											this.reversedImage = res.tempFilePath;
										}
									}, this);
								}
							}, this);
						}
					}, this);
				});
				ctx.setFillStyle('#ffffff')
				// 倒置Canvas
				// ctx.translate(width / 2, height / 2);
				// ctx.rotate(Math.PI);
				// ctx.translate(-width / 2, -height / 2);

				ctx.fillRect(0, 0, width, height) // 填充整个画布
				ctx.drawImage(url, 0, 0, width, height)
				ctx.draw();
				setTimeout(() => {
					callback.call(null, ctx)
				}, 500)
				// 把图片渲染到canvas上，延迟500ms进入回调
				// 如果图片渲染太慢，可以加大回调时间进行测试
				// uni.chooseImage({
				// 	success: function(res) {
				// 		ctx.setFillStyle('#ffffff'); // 设置背景颜色为红色
				// 		ctx.fillRect(0, 0, width, height); // 填充整个画布
				// 		ctx.drawImage(res.tempFilePaths[0], 0, 0, width, height);
				// 		ctx.draw();
				// 		// 把图片渲染到canvas上，延迟500ms进入回调
				// 		// 如果图片渲染太慢，可以加大回调时间进行测试
				// 		setTimeout(() => {
				// 		    callback.call(null, ctx)
				// 		}, 500)
				// 	}
				// });
			},
			writeBLECharacteristicValue(printerJobs) {
				if (!this.currentDevice) {
					uni.showModal({
						title: '',
						content: '未连接，请先连接蓝牙设备！',
						showCancel: false
					});
					return;
				}
				let buffer = printerJobs.buffer();
				console.log('ArrayBuffer', 'length: ' + buffer.byteLength, 'buffer:' + Array.from(buffer), ' hex: ' +
					arrayBufferToHex(buffer));
				// 1.并行调用多次会存在写失败的可能性
				// 2.建议每次写入不超过20字节
				// 分包处理，延时调用
				const maxChunk = 20;
				for (let i = 0, j = 0, length = buffer.byteLength; i < length; i += maxChunk, j++) {
					let subPackage = buffer.slice(i, i + maxChunk <= length ? i + maxChunk : length);
					this.writeBLECharacteristicValueFun(subPackage);
					// setTimeout(this._writeBLECharacteristicValue, 10, subPackage);//有问题时在加延迟
				}
			},

			writeBLECharacteristicValueFun(buffer) {
				const deviceId = this.currentDevice.deviceId;
				const serviceId = this.currentDevice.serviceId;
				const characteristicId = this.currentDevice.characteristicId;
				uni.writeBLECharacteristicValue({
					deviceId,
					serviceId,
					characteristicId,
					value: buffer,
					success(res) {
						console.log('writeBLECharacteristicValue success', res);
					},
					fail(res) {
						console.log('writeBLECharacteristicValue fail', res);
					}
				});
			}
		}
	};
</script>
<style>
	.print {
		padding: 10rpx 30rpx;
	}


	.button-area {
		margin: 40rpx 0;
	}
</style>

<style lang="scss" scoped>
	.canvas {
		// transform: rotate(180deg);
	}
</style>